/**
 * 真实支付控制器
 * 处理第三方支付相关的API请求
 */
const { PrismaClient } = require('@prisma/client');
const { PaymentServiceFactory } = require('../services/paymentService');


const prisma = new PrismaClient();

/**
 * 创建支付订单
 */
exports.createPayment = async (req, res) => {
  try {
    const { orderId, paymentMethod, amount, description } = req.body;

    // 验证订单是否存在
    const order = await prisma.order.findUnique({
      where: { id: Number(orderId) },
      include: {
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      }
    });

    if (!order) {
      return res.status(404).json({
        status: 'error',
        message: '订单不存在'
      });
    }

    // 检查订单是否已支付
    if (order.status === 'paid' || order.status === 'completed') {
      return res.status(400).json({
        status: 'error',
        message: '订单已支付'
      });
    }

    // 现金支付直接标记为完成
    if (paymentMethod === 'cash') {
      const payment = await prisma.payment.create({
        data: {
          orderId: Number(orderId),
          method: paymentMethod,
          amount: Number(amount),
          status: 'completed',
          paidTime: new Date(),
          verifyStatus: 'verified'
        }
      });

      // 更新订单状态
      await prisma.order.update({
        where: { id: Number(orderId) },
        data: { status: 'paid' }
      });

      return res.json({
        status: 'success',
        message: '现金支付成功',
        data: {
          paymentId: payment.id,
          status: 'completed'
        }
      });
    }

    // 第三方支付处理
    try {
      const paymentService = await PaymentServiceFactory.createService(paymentMethod);
      
      const paymentResult = await paymentService.createPayment({
        orderId: order.orderNo,
        amount: Number(amount),
        description: description || `订单${order.orderNo}支付`
      });

      if (paymentResult.success) {
        // 创建支付记录
        const payment = await prisma.payment.create({
          data: {
            orderId: Number(orderId),
            method: paymentMethod,
            amount: Number(amount),
            status: 'pending',
            transactionId: paymentResult.transactionId,
            prepayId: paymentResult.prepayId,
            qrCode: paymentResult.qrCode,
            expireTime: new Date(Date.now() + 15 * 60 * 1000) // 15分钟过期
          }
        });

        // 记录审计日志
        await logAudit({
          userId: req.user?.id || 1,
          action: 'create',
          module: 'payment',
          description: `创建${paymentMethod}支付订单`,
          details: JSON.stringify({ orderId, paymentId: payment.id, amount })
        });

        res.json({
          status: 'success',
          message: '支付订单创建成功',
          data: {
            paymentId: payment.id,
            qrCode: paymentResult.qrCode,
            transactionId: paymentResult.transactionId,
            expireTime: payment.expireTime
          }
        });
      } else {
        res.status(400).json({
          status: 'error',
          message: '创建支付订单失败',
          error: paymentResult.error
        });
      }
    } catch (error) {
      console.error('第三方支付服务错误:', error);
      res.status(500).json({
        status: 'error',
        message: '支付服务暂时不可用',
        error: error.message
      });
    }
  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.status(500).json({
      status: 'error',
      message: '创建支付订单失败',
      error: error.message
    });
  }
};

/**
 * 查询支付状态
 */
exports.queryPaymentStatus = async (req, res) => {
  try {
    const { paymentId } = req.params;

    const payment = await prisma.payment.findUnique({
      where: { id: Number(paymentId) },
      select: {
        id: true,
        orderId: true,
        method: true,
        amount: true,
        status: true,
        createdAt: true,
        updatedAt: true,
        order: true
      }
    });

    if (!payment) {
      return res.status(404).json({
        status: 'error',
        message: '支付记录不存在'
      });
    }

    // 如果已经是完成状态，直接返回
    if (payment.status === 'completed') {
      return res.json({
        status: 'success',
        data: {
          paymentStatus: 'completed',
          paidTime: payment.paidTime
        }
      });
    }

    // 现金支付不需要查询
    if (payment.method === 'cash') {
      return res.json({
        status: 'success',
        data: {
          paymentStatus: payment.status
        }
      });
    }

    // 查询第三方支付状态
    try {
      const paymentService = await PaymentServiceFactory.createService(payment.method);
      const queryResult = await paymentService.queryPayment(payment.transactionId);

      if (queryResult.success) {
        let newStatus = payment.status;
        let paidTime = payment.paidTime;

        // 根据第三方返回状态更新本地状态
        if (queryResult.status === 'SUCCESS' || queryResult.status === 'TRADE_SUCCESS') {
          newStatus = 'completed';
          paidTime = new Date(queryResult.paidTime || Date.now());

          // 更新支付记录
          await prisma.payment.update({
            where: { id: payment.id },
            data: {
              status: 'completed',
              paidTime: paidTime,
              verifyStatus: 'verified'
            }
          });

          // 更新订单状态
          await prisma.order.update({
            where: { id: payment.orderId },
            data: { status: 'paid' }
          });

          // 记录审计日志
          await logAudit({
            userId: req.user?.id || 1,
            action: 'update',
            module: 'payment',
            description: `支付完成确认`,
            details: JSON.stringify({ paymentId: payment.id, transactionId: payment.transactionId })
          });
        } else if (queryResult.status === 'CLOSED' || queryResult.status === 'TRADE_CLOSED') {
          newStatus = 'failed';
          await prisma.payment.update({
            where: { id: payment.id },
            data: {
              status: 'failed',
              failureReason: '支付已关闭'
            }
          });
        }

        res.json({
          status: 'success',
          data: {
            paymentStatus: newStatus,
            paidTime: paidTime,
            thirdPartyStatus: queryResult.status
          }
        });
      } else {
        res.status(400).json({
          status: 'error',
          message: '查询支付状态失败',
          error: queryResult.error
        });
      }
    } catch (error) {
      console.error('查询第三方支付状态错误:', error);
      res.status(500).json({
        status: 'error',
        message: '支付状态查询服务暂时不可用',
        error: error.message
      });
    }
  } catch (error) {
    console.error('查询支付状态失败:', error);
    res.status(500).json({
      status: 'error',
      message: '查询支付状态失败',
      error: error.message
    });
  }
};

/**
 * 处理支付回调
 */
exports.handlePaymentCallback = async (req, res) => {
  try {
    const { paymentMethod } = req.params;
    const callbackData = req.body;

    console.log(`收到${paymentMethod}支付回调:`, callbackData);

    const paymentService = await PaymentServiceFactory.createService(paymentMethod);
    const callbackResult = await paymentService.handleCallback(callbackData);

    if (callbackResult.success) {
      // 查找对应的支付记录
      const payment = await prisma.payment.findFirst({
        where: {
          transactionId: callbackResult.transactionId,
          method: paymentMethod
        },
        include: { order: true }
      });

      if (payment) {
        // 更新支付记录
        await prisma.payment.update({
          where: { id: payment.id },
          data: {
            status: 'completed',
            paidTime: new Date(callbackResult.paidTime || Date.now()),
            notifyData: JSON.stringify(callbackData),
            verifyStatus: 'verified'
          }
        });

        // 更新订单状态
        await prisma.order.update({
          where: { id: payment.orderId },
          data: { status: 'paid' }
        });

        // 记录审计日志
        await logAudit({
          userId: 1, // 系统操作
          action: 'callback',
          module: 'payment',
          description: `${paymentMethod}支付回调处理成功`,
          details: JSON.stringify({
            paymentId: payment.id,
            orderId: payment.orderId,
            transactionId: callbackResult.transactionId
          })
        });

        console.log(`支付回调处理成功: 订单${payment.order.orderNo}`);
      } else {
        console.warn(`未找到对应的支付记录: ${callbackResult.transactionId}`);
      }

      // 返回成功响应给第三方
      if (paymentMethod === 'wechat') {
        res.set('Content-Type', 'application/xml');
        res.send('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
      } else if (paymentMethod === 'alipay') {
        res.send('success');
      }
    } else {
      console.error('支付回调验证失败:', callbackResult.error);
      
      if (paymentMethod === 'wechat') {
        res.set('Content-Type', 'application/xml');
        res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[验证失败]]></return_msg></xml>');
      } else if (paymentMethod === 'alipay') {
        res.send('fail');
      }
    }
  } catch (error) {
    console.error('处理支付回调失败:', error);
    
    if (req.params.paymentMethod === 'wechat') {
      res.set('Content-Type', 'application/xml');
      res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>');
    } else {
      res.send('fail');
    }
  }
};

/**
 * 申请退款
 */
exports.refundPayment = async (req, res) => {
  try {
    const { paymentId } = req.params;
    const { refundAmount, reason } = req.body;

    const payment = await prisma.payment.findUnique({
      where: { id: Number(paymentId) },
      include: { order: true }
    });

    if (!payment) {
      return res.status(404).json({
        status: 'error',
        message: '支付记录不存在'
      });
    }

    if (payment.status !== 'completed') {
      return res.status(400).json({
        status: 'error',
        message: '只能对已完成的支付申请退款'
      });
    }

    const refundAmountNum = Number(refundAmount);
    if (refundAmountNum <= 0 || refundAmountNum > payment.amount) {
      return res.status(400).json({
        status: 'error',
        message: '退款金额无效'
      });
    }

    // 现金退款直接处理
    if (payment.method === 'cash') {
      await prisma.payment.update({
        where: { id: payment.id },
        data: {
          status: 'refunded',
          failureReason: reason || '现金退款'
        }
      });

      return res.json({
        status: 'success',
        message: '现金退款成功',
        data: {
          refundAmount: refundAmountNum
        }
      });
    }

    // 第三方支付退款
    try {
      const paymentService = await PaymentServiceFactory.createService(payment.method);
      const refundId = `RF${Date.now()}${payment.id}`;
      
      const refundResult = await paymentService.refund({
        orderId: payment.order.orderNo,
        refundId: refundId,
        amount: payment.amount,
        refundAmount: refundAmountNum
      });

      if (refundResult.success) {
        await prisma.payment.update({
          where: { id: payment.id },
          data: {
            status: 'refunded',
            refundId: refundResult.refundId,
            failureReason: reason || '退款'
          }
        });



        res.json({
          status: 'success',
          message: '退款申请成功',
          data: {
            refundId: refundResult.refundId,
            refundAmount: refundAmountNum
          }
        });
      } else {
        res.status(400).json({
          status: 'error',
          message: '退款申请失败',
          error: refundResult.error
        });
      }
    } catch (error) {
      console.error('第三方退款服务错误:', error);
      res.status(500).json({
        status: 'error',
        message: '退款服务暂时不可用',
        error: error.message
      });
    }
  } catch (error) {
    console.error('申请退款失败:', error);
    res.status(500).json({
      status: 'error',
      message: '申请退款失败',
      error: error.message
    });
  }
};

module.exports = {
  createPayment: exports.createPayment,
  queryPaymentStatus: exports.queryPaymentStatus,
  handlePaymentCallback: exports.handlePaymentCallback,
  refundPayment: exports.refundPayment
};
